package com.lvhr.rpc.filter;

import com.lvhr.rpc.model.RpcRequest;
import com.lvhr.rpc.utils.SignatureUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.HmacUtils;

/**
 * HMAC-SHA256签名校验器
 */
@Slf4j
public class SignatureValidator implements SecurityValidator {
    private final String secretKey;
    private static final String SIGNATURE_HEADER = "X-Signature";

    public SignatureValidator(String secretKey) {
        this.secretKey = secretKey;
    }

    @Override
    public boolean validate(RpcRequest request) throws SecurityException {
        // 1. 获取签名和请求数据
        String receivedSign = (String) request.getAttachments().get(SIGNATURE_HEADER);
        if (receivedSign == null) {
            throw new SecurityException(403, "缺少签名参数");
        }
        // 2. 构造待签名字符串（按参数名排序后拼接）
        String signContent = SignatureUtils.buildSignContent(request);

        // 3. 计算HMAC-SHA256
        String calculatedSign = null;
        try {
            log.debug("开始签名校验 : {}",SignatureUtils.hmacSha256("salt",signContent));
            calculatedSign = SignatureUtils.hmacSha256(secretKey,signContent);
        } catch (Exception e) {
            e.printStackTrace();
        }
//        log.debug("客户端签名: {}", receivedSign);
//        log.debug("服务端计算签名: {}", calculatedSign);
//        log.debug("签名内容: {}", signContent);
//        log.debug("key内容: {}", secretKey);

        // 4. 比对签名
        if (!calculatedSign.equals(receivedSign)) {
            throw new SecurityException(403, "签名验证失败");
        }
        return true;
    }

}
